package com.cqie.secondhandtransaction.controller;

import com.cqie.secondhandtransaction.DTO.ChatInfoDTO;
import com.cqie.secondhandtransaction.entity.ChatInfo;
import com.cqie.secondhandtransaction.handler.ChatHandler;
import com.cqie.secondhandtransaction.message.ChatMessage;
import com.cqie.secondhandtransaction.model.Result;
import com.cqie.secondhandtransaction.service.ChatInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gdy
 * @since 2025-02-10
 */
@RestController
@RequestMapping("/chat")
@Api(value = "聊天管理", tags = {"聊天管理"})
@Slf4j
public class ChatInfoController extends BaseController {

    @Autowired
    private ChatInfoService chatInfoService;

    @PostMapping("/saveMessage")
    @ApiOperation(value = "发送消息")
    public Result<?> saveMessage(@RequestBody ChatMessage message) {
        ChatInfo chatInfo = new ChatInfo();
        BeanUtils.copyProperties(message,chatInfo);
        chatInfo.setSenderType(String.valueOf(message.getSenderType()));
        chatInfoService.saveMessage(chatInfo);

        try {
            ChatHandler.broadcastMessage(chatInfo); // 广播消息
        } catch (Exception e) {
            log.error("Failed to broadcast message", e);
        }


        return response();
    }

    @GetMapping("/getMessages")
    @ApiOperation(value = "消息列表")
    public Result<List<ChatInfoDTO>> getMessages(@RequestParam String chatCode) {
        return response(chatInfoService.getMessagesByChatCode(chatCode));
    }
}
